package com.example.asynctaskdemo.okhttp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import com.example.asynctaskdemo.Util;
import okhttp3.Request;
import okhttp3.Response;
import java.lang.ref.WeakReference;

/**
 * Created by Administrator on 2016/11/7.
 */
public class PostTask<T> extends AsyncTask<Void, Void, T> {

    private Class<T> classOfT;
    private WeakReference<Activity> act;
    private ResultListener<T> listener;
    private Request request;
    private boolean isShowDialog;


    public PostTask(Activity activity, Class<T> clazz, Request request, boolean isShowDialog, ResultListener<T> lis) {
        this.act = new WeakReference<>(activity);
        this.classOfT = clazz;
        this.request = request;
        this.isShowDialog = isShowDialog;
        this.listener = lis;
    }

    @SuppressLint("NewApi")
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected T doInBackground(Void... params) {
        try {
            Response response = OkHttpUtil.getClient().newCall(request).execute();
            if (response == null || !response.isSuccessful()) {
                return null;
            }

            String result = response.body().string();

            if (TextUtils.isEmpty(result)) {
                return null;
            }

            Log.e("kunge.hu", result);

            T t = Util.parseStr2Bean(result, classOfT);

            return t;
        } catch (Exception e) {
            Log.e("kunge.hu", "PostTask Exception:" + e.toString());
        }

        return null;
    }

    @SuppressLint("NewApi")
    @Override
    protected void onPostExecute(T t) {
//        try {
//            if (dialog != null) {
//                dialog.dismiss();
//            }
//        } catch (Exception e) {
//            Log.e("kunge.hu", "PostTask Dialog Exception:" + e.toString());
//        }
//
//        Activity a = act.get();
//        if (a != null && !a.isFinishing() && !a.isDestroyed()) {
//            if (listener != null) {
//                if (t == null) {
//                    listener.error(0, "网络异常，请稍后再试");//异常
//                } else {
//                    listener.succ(t);
//                }
//            }
//        } else {
//            listener = null;
//            Log.e("kunge.hu", "activity is recyled!!!");
//        }





    }
}
